<?php

class SaleController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
        $this->view->getcontroller = Zend_Controller_Front::getInstance()->getRequest()->getControllerName();
        $this->view->getaction = Zend_Controller_Front::getInstance()->getRequest()->getActionName();
        $core = new Model_Core();
        $this->view->config = $core->getConfig();
        
        if ($core->islogin()){
            $this->view->member = $core->isLogin();
        }
        
        $this->view->nowtitle = "我要卖车";
        
        $this->view->ref = urlencode("http://".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]);
        
        $this->_helper->layout->setLayout('sale');
    }
    
    protected function getProfile(){
        $core = new Model_Core();
        
        if ($core->islogin()){
            return $core->islogin();
        }else{
            return false;
        }

    }
    
    public function indexAction() {

        
        $carmodel = new Model_CarModel();
        $this->view->allbrand = $carmodel->getAllBrand();
        
        $carcolor = new Model_CarColor();
        $this->view->allcolor = $carcolor->getAllColor();
        
        $allcity = new Model_City();
        $this->view->allcity = $allcity->getAllCity();
        
        $submod = trim($this->_request->getParam('submod'));
        
        $modeldata = "";
        $citydata = "";

        $db = new Model_CarSale();
        $core = new Model_Core();

        $u_profile = $this->getProfile();
        
        if ($u_profile){
            //联系人名称使用PROFILE表中的真实姓名
            $data[u_contact_user] = $u_profile[username];
            $data[u_contact_tel] = $u_profile[phone];
        }else{
            $u_profile[uid] = 0;
            //匿名用户  不允许发布第二条
            if ($_COOKIE['is_sale']){
            	$this->_forward('nmerror');
            }
        }
        
        
        //用户被BAN
        if ($u_profile[ban] == 2){
            $this->_forward('isbaned','set');
        }
        


        //提交表单
        if ($submod) {
            
            
            $data = $_POST;
            $is_check = $core->checkSale($data);
            
            //PHP CHECKED
            if ($is_check[flag] == 0) {
                $time = time();
                
                $data[title] = "";
				if ($data[carname] == '-1'){
				    $data[title] .= '其他品牌';
				}else{
				    $modeltitle = $carmodel->getModelName($data[carname]);
				    
				    if ($data[is_write] == 0){
				    	$data[title] .= $modeltitle[name];
				    }else{
				    	$data[title] .= $modeltitle[model]." ".$data[model_text];
				    }
				}
				$data[title] .= " ".$data[car_year]."年上牌";
				
                if ($data[kilometer] < 100) {
                	$data[kilometer] = $data[kilometer] * 10000;
                }
                //换成单位万元
                if ($data[price] > 10000) {
                	$data[price] = number_format($data[price] / 10000, 2, '.', '');
                }
                $data[note] = strip_tags($data[note]);
                $color_data = $carcolor->getColorName($data[color]);
                
                /*
                $tcl_session = new Zend_Session_Namespace('taochele');
                $c = "arr_".$data[session_id];
                $tcl_session->$c = '2222222';
                */

                
                //echo $data[session_id];
                $img_arr = $data[pic_arr];
                $front = $data[front] ? $data[front] : $img_arr[0];

                
				
                if ($front){
                    $img_dir = "/uploads/img/".date(Y)."/".date(m)."/".date(d)."/";
                    //$img_dir = "http://img.taochele.com/".date(Y)."/".date(m)."/".date(d)."/";
                }else{
                    $img_dir = "/img/";
                    $front = "noimg.gif";
                    $img_arr[0] = "noimg.gif";
                }
                
                $img_arr = serialize($img_arr);
                $note = $core->cutstr(htmlspecialchars($data[note]), 480);
                
                
                $save_data = array(
                	'title' 		=> "$data[title]",
                	'note'			=> "$note",
                	'province_id'	=> "$data[province]",
                	'city_id'		=> "$data[city]",
                	'brand_id'		=> "$data[brand]",
                	'model_id'		=> "$data[model]",
                	'name_id'		=> "$data[carname]",
                	'color_id'		=> "$data[color]",
                    'color_value'	=> "$color_data[color_value]",
                    'color_name'	=> "$color_data[color_name]",
                	'contact_user'	=> "$data[contact_user]",
                	'contact_tel'	=> "$data[contact_tel]",
                	'uid'			=> $u_profile[uid],
                	'kilometer'		=> "$data[kilometer]",
                	'price'			=> "$data[price]",
                	'car_year'		=> "$data[car_year]",
                	'car_month'		=> "$data[car_month]",
                	'safe_year'		=> "$data[safe_year]",
                	'safe_month'	=> "$data[safe_month]",
                	'check_year'	=> "$data[check_year]",
                	'check_month'	=> "$data[check_month]",
                	'car_operate'	=> "$data[car_operate]",
                	'maintenance'	=> "$data[maintenance]",
                	'company_id'	=> 0,
                	'is_app'		=> 1,
                    'session_id'    => $data[session_id],
                    'car_img'       => $front,
                	'img_dir'       => $img_dir,
                    'img_arr'       => $img_arr,
                	'created_at'	=> $time
                );

                
                if ($submod == 'add') {
                	//INSERT DB
	                $id = $db->setSalePost($save_data);
	                if ($id) {
	                    
	                    //匿名用户 写入COOKIE 86400一天
	                    if ($u_profile[uid] == 0){
	                        setcookie('is_sale', "1", time() + 86400);
	                    }
	                    
	                	$this->_redirect("/sale/success/cid/$id");
	                }else{
	                    $this->_forward('error');
	                }
	                
                }else{
                    //UPDATE
                    $row = $db->setSaleUpdate($save_data, $data[cid], $u_profile[uid]);
                    if ($row) {
                    	$this->_redirect("/sale/success/cid/$data[cid]");
                    }else{
                    	$this->_forward('error');
                    }
                }
                
                
            }else{
                $this->view->geterror = $is_check[err_str];
            }
            

        }else{
            $tcl_session = new Zend_Session_Namespace('taochele');
            $tcl_session->upload_num = 0;
            $now = time();
            $this->view->session_id = $now.rand("1234", "9999");
            
        }

        //IN EDIT OR POST PHPERROR
        //print_r($_POST);
        
        $op = trim($this->_request->getParam('op', 'add'));
        $cid = intval($this->_request->getParam('cid'));
        $this->view->cid = $cid;
        
        if ($op == "edit"){

            $db_data = $db->getViewName($cid);
            foreach ($db_data as $value){
                $data[uid] = $value[uid];
                $data[brand] = $value[brand_id];
                $data[model] = $value[model_id];
                $data[carname] = $value[name_id];
                $data[is_write] = 0; //不为0时 应为手动输入
                $data[color] = $value[color_id];
                $data[province] = $value[province_id];
                $data[city] = $value[city_id];
                $data[kilometer] = $value[kilometer];
                $data[car_year] = $value[car_year];
                $data[car_month] = $value[car_month];
                $data[check_year] = $value[check_year];
                $data[check_month] = $value[check_month];
                $data[safe_year] = $value[safe_year];
                $data[safe_month] = $value[safe_month];
                $data[car_operate] = $value[car_operate];
                $data[maintenance] = $value[maintenance];
                $data[note] = $value[note];
                $data[price] = $value[price];
                $data[contact_user] = $value[contact_user];
                $data[contact_tel] = $value[contact_tel];
                if ($value[name_id] == -1){
                    $data[is_write] = 1;
                    $data[model_text] = $value[title];
                }
                $this->view->session_id = $value[session_id];
                $data[front] = $value[car_img];
                $data[img_dir] = $value[img_dir];
                $data[img_arr] = unserialize($value[img_arr]);
            }
            
            //UID与登陆UID不符合   管理员可操作
            if ($data[uid] != $u_profile[uid] && $u_profile[groupid] != 1){
                if (!$u_profile[uid]){
                    $this->_redirect("/member/login?ref=".urlencode("http://".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"])."");
                }else{
                    $this->view->error = 'uid_error';
                    $this->_forward('nmerror');
                }
                exit();
            }
        }
        
        
        $this->view->getdata = $data;
        
        //用于 edit
        //如果有BRAND 输出MODEL
        if ($data[brand]) {
        	$carmodel = new Model_CarModel();
        	$modeldata = $carmodel->getModel($data[brand]);
        	if ($data[model]){
        		$carnamedata = $carmodel->getCarname($data[model]);
        	}
        }
        //如果有省 输出市
        if ($data[province]) {
        	$city_arr = new Model_City();
        	$citydata = $city_arr->getCityChild($data[province]);
        }
             

        $this->view->op = $op;
        $this->view->citydata = $citydata;
        $this->view->modeldata = $modeldata;
        $this->view->carnamedata = $carnamedata;
        
        $this->view->headTitle("免费发布您的卖车信息", 'PREPEND');
        $this->view->headMeta()->setName('keywords', "免费发布您的卖车信息");
        $this->view->headMeta()->setName('description', "免费发布您的卖车信息");
    }
    
    
    public function successAction() {
		
        $cid = trim($this->_request->getParam('cid'));
        if ($cid) {
            $carsale = new Model_CarSale();
            $row = $carsale->getView($cid);
            
            $this->view->row = $row;
        	$this->view->cid = $cid;
        }else{
            $this->errorAction();
        }
        
    }
    
    public function errorAction(){
        echo '<h1>DateBase Error!</h1>';
        echo "<a href='javascript:history.go(-1)'>返回重试</a>";
        exit();
    }

    
    //匿名用户 不允许发布第二条
    public function nmerrorAction() {
    	
    }
    
}

